package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Override
    public void insertWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //新增一个菜品
        dishMapper.insert(dish);
        Long dishId = dish.getId();
        //新增n个口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach((flavor) -> flavor.setDishId(dishId));
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional//同时删除多个表要加事务
    public void batchDelete(List<Long> ids) {
//        //首先从ids中提取id参数
//        String[] splits = ids.split(",");
//        //把他们都放到集合中
//        List<Long> list = Arrays.stream(splits).map(Long::valueOf).collect(Collectors.toList());


//        if (list == null || list.isEmpty()) {
//            return;
//        }
        for (Long dishId : ids) {
            //起售中的菜品不能删除
            //获取每个菜品的状态
            Integer status = dishMapper.getStatusById(dishId);
            if (status.equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
//            判断菜品是不是与套餐关联
//            setmeal_dish表中按dish的id对应表中的dish_id查询是不是有对应的套餐.如果count>0就不能删除

            Integer count = setMealDishMapper.countByDishId(dishId);
            if (count > 0) {
                //说明当前菜品有关联套餐,不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //批量删除菜品
        dishMapper.batchDelete(ids);
        //删除菜品的时候要把关联的口味数据也要删除掉
        dishFlavorMapper.batchDelete(ids);


    }


    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getDishWithFlavorsByDishId(Long id) {

        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.getById(id);
        BeanUtils.copyProperties(dish, dishVO);

        //添加口味属性
        List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorsByDishId(id);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //先把菜品id对应的风味数据删除
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //再把风味数据插入
        //记得判断分为数据是否为空,且设置菜品id进去
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            flavors.forEach((flavor) -> flavor.setDishId(dishDTO.getId()));
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }


    /**
     * 根据分类id查询
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listByCategoryId(Long categoryId) {
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        List<Dish> dishs = dishMapper.getByCategoryId(dish);
        //用糊涂包的方法简化
//        List<DishVO> dishVOS = BeanUtil.copyToList(dishs, DishVO.class);

        ArrayList<DishVO> dishVOS = new ArrayList<>(dishs.size());
        for (Dish d : dishs) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            dishVOS.add(dishVO);
        }
        return dishVOS;
    }

    /**
     * 修改菜品状态
     * @param status
     * @param id
     */
    @Override
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.udapteDishStatus(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorsByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
